﻿using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Shapes;

namespace MultiSliderSample
{
    /// <summary>
    /// 扩展Thumb
    /// </summary>
    public class ThumbEx : Thumb
    {
        #region 字段
        private Rectangle _leftRect;
        private Rectangle _rightRect;
        private RangeItem _leftRangeItem;
        private RangeItem _rightRangeItem;
        private double _maxWidth = 330;
        #endregion

        #region 属性
        public List<ThumbEx> ThumbExs
        {
            get; set;
        }
        #endregion

        #region 构造
        public ThumbEx(Rectangle leftRect, Rectangle rightRect, RangeItem leftRangeItem, RangeItem rightRangeItem)
        {
            _leftRect = leftRect;
            _rightRect = rightRect;
            _leftRangeItem = leftRangeItem;
            _rightRangeItem = rightRangeItem;
            this.DragDelta += ThumbEx_DragDelta;
            this.DragStarted += ThumbEx_DragStarted;
            this.DragCompleted += ThumbEx_DragCompleted;
        }
        #endregion

        #region 开始滑动时，将ZIndex设置为最上面，防止两个滑块叠加不能拖动的情况
        private void ThumbEx_DragStarted(object sender, DragStartedEventArgs e)
        {
            ThumbExs.ForEach(thumb =>
            {
                Canvas.SetZIndex(thumb, 0);
            });

            Canvas.SetZIndex(this, 1);
        }
        #endregion

        #region 拖动时
        private void ThumbEx_DragDelta(object sender, DragDeltaEventArgs e)
        {
            if ((_leftRect.Width + e.HorizontalChange) >= 0 && (_rightRect.Width - e.HorizontalChange) >= 0)
            {
                _leftRect.Width += e.HorizontalChange;
                _rightRect.Width -= e.HorizontalChange;

                var sliderLeft = Canvas.GetLeft(this);
                sliderLeft += e.HorizontalChange;
                Canvas.SetLeft(this, sliderLeft);
            }
        }
        #endregion

        #region 结束时，计算值
        private void ThumbEx_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            if (_leftRect.Width == 0)
            {
                _leftRangeItem.Duration = 0;
            }
            else
            {
                _leftRangeItem.Duration = _rightRect.Width / _maxWidth * _leftRangeItem.MaxDuration;
            }

            if (_rightRect.Width == 0)
            {
                _rightRangeItem.Duration = 0;
            }
            else
            {
                _rightRangeItem.Duration = _rightRect.Width / _maxWidth * _rightRangeItem.MaxDuration;
            }
        }
        #endregion
    }
}